//
//  BoardView.swift
//  Calculator
//  自定义类
//  Created by 白瑾浩 on 2022/1/12.
//

import UIKit

class BoardView: UIView {
    var delegate:BoardButtonInputDelegate?
    var dataArray = ["0",".","%","=",
                     "1","2","3","+",
                     "4","5","6","-",
                     "7","8","9","*",
                     "AC","Del","^","/"]
    override init( frame:CGRect ){
        super.init( frame: frame )
        installUI()
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    func installUI(){
        var  frontBtn : FuncButton!
        
        for index in 0..<dataArray.count{
            //建立button
            let btn = FuncButton()
            self.addSubview( btn )   //插入到父类
            
            btn.snp.makeConstraints { make in
                
                
                //当按钮每一行第一个时  距离左边为0
                if index % 4 == 0 {
                    make.left.equalTo( 0 )
                }else{
                    make.left.equalTo( frontBtn.snp.right )
                }
                
                //当按钮为第一行时，将其靠父视图底部摆放
                if index/4 == 0 {
                    make.bottom.equalTo( 0 )
                //当按钮不在第一行且每行的第一个时，将其底部与上一个按钮的顶部对齐
                }else if index % 4 == 0 {
                    make.bottom.equalTo( frontBtn.snp.top )
                    //否则将其底部与上一个按钮的底部对齐
                }else{
                    make.bottom.equalTo( frontBtn.snp.bottom )
                }
                //宽是父类宽度的0.25
                make.width.equalTo( btn.superview!.snp.width ).multipliedBy(0.25)
                //高度是类类高度的 0.2
                make.height.equalTo( btn.superview!.snp.height ).multipliedBy(0.2)
                
                
            }
            
            btn.tag = index + 100
            
            btn.addTarget(self, action: #selector(btnClick), for: UIControl.Event.touchUpInside)
            
            btn.setTitle( dataArray[index], for: UIControl.State.normal)
            
            
            frontBtn = btn
            
        }
        
        
        
    }
    //通过协议传值
    @objc func btnClick(_ button:FuncButton ){
        
        print( button.title(for: UIControl.State.normal )! )
        delegate?.boardButtonClick(Content: button.currentTitle!  )
        
    }
    
}

//定义协议传值
protocol BoardButtonInputDelegate {
    func boardButtonClick(Content:String)
}
